package top.vchao.webmusicplayer.player;

/**
 * @ Create_time: 2019/8/27 on 10:36.
 * @ description：
 * @ author: vchao
 */

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Handler;
import android.util.Log;
import android.widget.SeekBar;

import top.vchao.webmusicplayer.utils.LogUtils;

public class Player implements OnBufferingUpdateListener, OnCompletionListener, OnPreparedListener {

    public MediaPlayer mediaPlayer; // 媒体播放器
    private SeekBar seekBar; // 拖动条
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            int position = mediaPlayer.getCurrentPosition();
            int duration = mediaPlayer.getDuration();
            if (duration > 0) {
                // 计算进度（获取进度条最大刻度*当前音乐播放位置 / 当前音乐时长）
                long pos = seekBar.getMax() * position / duration;
                seekBar.setProgress((int) pos);
            }

        }

        ;
    };
    // 计时器
    TimerTask timerTask = new TimerTask() {

        @Override
        public void run() {
            if (mediaPlayer == null)
                return;
            if (mediaPlayer.isPlaying() && seekBar.isPressed() == false) {
                handler.sendEmptyMessage(0); // 发送消息
            }
        }
    };
    private Timer mTimer = new Timer(); // 计时器
    private int mLastProgress;
    private boolean isDraggingProgress;
    private String music_name;
    private String music_url;
    private PlayStateInterface playStateInterface;

    // 初始化播放器
    public Player(SeekBar seekBar) {
        super();
        this.seekBar = seekBar;
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);// 设置媒体流类型
            mediaPlayer.setOnBufferingUpdateListener(this);
            mediaPlayer.setOnPreparedListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 每一秒触发一次
        mTimer.schedule(timerTask, 0, 1000);
        LogUtils.e("seekBar.getMax() == " + seekBar.getMax());
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                LogUtils.e("-----------  onProgressChanged -----------  " + progress);
                mLastProgress = progress;
                if (mLastProgress > 99) {
                    playStateInterface.playEnd();
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                LogUtils.e("-----------  onStartTrackingTouch -----------");
                isDraggingProgress = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                LogUtils.e("-----------  onStopTrackingTouch -----------");
                isDraggingProgress = false;
                seekBar.setProgress(mLastProgress);
                int duration = mediaPlayer.getDuration();
                int progress = seekBar.getProgress() * duration / seekBar.getMax();
                mediaPlayer.seekTo(progress);
            }
        });
    }

    public void play() {
        mediaPlayer.start();
    }

    public void setPlayStateInterface(PlayStateInterface playStateInterface) {
        this.playStateInterface = playStateInterface;
    }

    /**
     * @param url url地址
     */
    public void playUrl(String url) {
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(url); // 设置数据源
            mediaPlayer.prepare(); // prepare自动播放
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 暂停
    public void pause() {
        mediaPlayer.pause();
    }

    // 继续
    public void resume() {
        mediaPlayer.start();
    }

    // 移动到百分比的进度
    public void seekTo(int progress) {
        seekBar.setProgress(progress);
        int duration = mediaPlayer.getDuration();
        mediaPlayer.seekTo(seekBar.getProgress() * duration / seekBar.getMax());
    }

    // 停止
    public void stop() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    // 播放准备
    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.start();
        Log.e("mediaPlayer", "onPrepared");
    }

    // 播放完成
    @Override
    public void onCompletion(MediaPlayer mp) {
        Log.e("zwc", "onCompletion");
        playStateInterface.playEnd();

    }

    /**
     * 缓冲更新
     */
    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        seekBar.setSecondaryProgress(percent);
        if (mediaPlayer.getDuration() != 0) {
            int currentProgress = seekBar.getMax() * mediaPlayer.getCurrentPosition() / mediaPlayer.getDuration();
            Log.e(currentProgress + "% play", percent + " buffer");
        } else {
            int currentProgress = 0;
        }
    }

    public int getmLastProgress() {
        return mLastProgress;
    }

    public void setmLastProgress(int mLastProgress) {
        this.mLastProgress = mLastProgress;
    }

    public String getMusic_name() {
        return music_name;
    }

    public void setMusic_name(String music_name) {
        this.music_name = music_name;
    }

    public String getMusic_url() {
        return music_url;
    }

    public void setMusic_url(String music_url) {
        this.music_url = music_url;
    }

    public interface PlayStateInterface {
        void playEnd();
    }
}
